package com.project.school_flate.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.licoy.encryptbody.annotation.decrypt.DecryptBody;
import cn.licoy.encryptbody.annotation.encrypt.EncryptBody;
import cn.licoy.encryptbody.enums.DecryptBodyMethod;
import cn.licoy.encryptbody.enums.EncryptBodyMethod;
import com.alibaba.fastjson2.JSON;
import com.project.school_flate.util.Result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author sunht
 * @Date 2023/7/15 18:19
 * @Version v1.0.0
 * @Message
 **/
//@Configuration
public class CorsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = null;
        //从参数拿token
        if(request.getParameter("publictoken") != null){
            token = request.getParameter("publictoken");
        }
        // 从 http 请求头中取出 token
        if(StringUtils.isBlank(token)){
            token = request.getHeader("publictoken");
        }
        if(StringUtils.isBlank(StpUtil.getTokenValue()) || StringUtils.isBlank(token)){
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(200);
            response.getWriter().write(JSON.toJSONString(Result.notLogin()));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        try{
            StpUtil.checkLogin();
        }catch (Exception e){
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(200);
//                response.getWriter().write(JSON.toJSONString(Result.failDown("您的账号已过期或在其他地方登录，请重新登录")));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        return true;
    }
    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        //System.out.println(new Date() + "--进入接口后:" + request.getRequestURL());
    }
    /**
     * postHandle方法执行完成后执行，一般用于释放资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        //System.out.println(new Date() + "---执行完成后:" + request.getRequestURL());
    }
}
